package com.whub507.msgmanager.sso.controller;

import com.whub507.msgmanager.common.Field;
import com.whub507.msgmanager.common.ResResult;
import com.whub507.msgmanager.mapper.UserMapper;
import com.whub507.msgmanager.sso.client.auth.AuthUtils;
import com.whub507.msgmanager.sso.client.auth.IdentityToken;
import com.whub507.msgmanager.sso.client.sso.SSOService;
import com.whub507.msgmanager.sso.client.sso.SimpleClientHttpRequestFactory4Https;
import com.whub507.msgmanager.sso.context.ContextUser;
import com.whub507.msgmanager.sso.util.DrapUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/login")
@Api(tags = "登录接口")
public class LoginController {

	private final static String SSO_CODE = "sso_code";

	/**
	 * 应用唯一标识,对应统一权限分系统中应用ID
	 */
	private String app_id = "sjdx";

	/**
	 * 查询当前用户对指定应用的的资源数，大于0表示具有访问应用权限
	 */
	@Value("${drap_platform.sso_server.rootpath}/context/ptaa_context/cntContextResourcePrivilege")
	private String cntContextResourcePrivilege_url;

	/**
	 * 查询当前用户应用内可操作的菜单集
	 */
	@Value("${drap_platform.sso_server.rootpath}/context/ptaa_context/qryAuthedAllMenu?app_id=app_demo_id")
	private String qryAuthedAllMenu_url;

	@Autowired
	private SSOService ssoService;

	@Resource
	private UserMapper userMapper;

	private RestTemplate restTemplate;

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@GetMapping
	public ResResult<ContextUser> login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			Object[] result = null;

			// 从url参数获取sso_code
			String sso_code = getSSOCodeFromQueryStr(request);
//			if (!ObjectUtils.isEmpty(sso_code)) {
//				// 换取token
//				result = ssoService.getIdentityTokenByCode(sso_code,app_id);
//			}
//
//			if (result == null) {
//				return ResResult.error(507, "sso_code is required.");
//			}
//
//			ContextUser user = AuthUtils.createContextUser((String) result[0], (IdentityToken) result[1]);
//			System.out.println(user.getUserName());
			List<String> roles=new ArrayList<>();
			ContextUser user =new ContextUser("0","default","瞿峰","default","default","default","default","default",roles );

			// 1 检查用户能否访问该应用,调用上下文用户相关接口需要header【ssotoken】，去掉下划线，nginx默认不支持
//			HttpHeaders requestHeaders = new HttpHeaders();
//			requestHeaders.setContentType(MediaType.APPLICATION_JSON);
//
//			requestHeaders.add("ssotoken", DrapUtils.validate((String) result[0]));

//			requestHeaders.add("ssotoken", sso_code);

//			Map<String, String> data = new HashMap<String, String>();
//			// 固定参数
//			data.put("resource_type", "pt_app");
//			// 固定参数
//			data.put("privilege_code", "access");
//			// 应用ID
//			data.put("resource_id", app_id);
//
//			HttpEntity<Map<String, String>> requestEntity = new HttpEntity<Map<String, String>>(data, requestHeaders);
//			List rest_result = restTemplate.postForObject(cntContextResourcePrivilege_url, requestEntity, List.class);
//
//			int count = Integer.parseInt(((Map<String, Object>) rest_result.get(0)).get("total").toString());
//			// 无权访问应用
//			if (count < 1) {
//				throw new RuntimeException("The user[" + user.getUserLoginName() + "] does not have access.");
//			}
//
//			// 2 获取用户在该应用内的权限
//			HttpEntity requestEntity2 = new HttpEntity(null, requestHeaders);
//			ResponseEntity<List> rest_result2 = restTemplate.exchange(qryAuthedAllMenu_url, HttpMethod.GET,
//					requestEntity2, List.class);
//			// 缓存权限集
//			request.getSession().setAttribute("menus", rest_result2.getBody());

			// 建立用户会话
			request.getSession().setAttribute("user", user);
			List<String> roleses=new ArrayList<>();

//			Integer userid = userMapper.selectByLoginName(user.getUserLoginName()).getId();
//
//			ContextUser resUser =new ContextUser(userid.toString(),"default",user.getUserName()
//					,"default","default","default",(user.getUserName().equals("瞿峰")) ? "common" : "admin","default", roleses );

			ContextUser resUser =new ContextUser("29","default",user.getUserName()
					,"default","default","default",(user.getUserName().equals("瞿峰")) ? "common" : "admin","default", roleses );

			// 登录成功跳转到应用首页
//			response.sendRedirect("http://100.81.20.208:9090/basic/home");
			List<Field> fields = new ArrayList<>();
			fields.add(new Field("userId", "用户ID"));
			fields.add(new Field("userName", "用户名"));
			fields.add(new Field("domainId", "权限"));

			return ResResult.ok(resUser,fields,"登录成功");

		} catch (Exception e) {
			e.printStackTrace();
			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().print(e.getMessage());
		}
		return ResResult.error(403,"登录失败");
	}


	private String getSSOCodeFromQueryStr(HttpServletRequest request) {
		String queryStr = request.getQueryString();
		if (queryStr != null) {
			String[] paras = queryStr.split("&");
			for (String s : paras) {
				String[] para = s.split("=");
				if (para.length == 2 && SSO_CODE.equals(para[0])) {
					return para[1];
				}
			}
		}
		return null;
	}

	@PostConstruct
	public void init() {
		SimpleClientHttpRequestFactory4Https requestFactory = new SimpleClientHttpRequestFactory4Https();

		requestFactory.setReadTimeout(120 * 1000);

		this.restTemplate = new RestTemplate(requestFactory);
	}

}
